package org.linkerproject.browser;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationAdapter;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class OperateWindow extends Dialog {

	protected Object result;

	protected Shell shell;

	private BrowserManager manager;

	/**
	 * Create the dialog
	 * 
	 * @param parent
	 * @param style
	 */
	public OperateWindow(Shell parent, int style) {
		super(parent, style);
	}

	/**
	 * Create the dialog
	 * 
	 * @param parent
	 */
	public OperateWindow(Shell parent) {
		this(parent, SWT.NONE);
	}

	public OperateWindow(Shell shell, BrowserManager manager) {
		this(shell);

		this.manager = manager;
	}

	public void setUrl(String url) {
		browser.setUrl(url);
	}

	/**
	 * Open the dialog
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		return result;
	}

	/**
	 * Create contents of the dialog
	 */
	protected void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shell.setLayout(new FillLayout());
		shell.setSize(516, 408);
		shell.setText("Cloud Operate");

		browser = new Browser(shell, SWT.NONE);
		initListener();
		//
	}

	private void initListener() {
		browser.addLocationListener(new LocationAdapter() {

			@Override
			public void changing(LocationEvent le) {
				if (!manager.isWebUrl(le.location)) {

					return;
				}

				browser.stop();
				String html = browser.getText();
				manager.save(lastUrl, html);
				manager.browse(le.location);
				shell.dispose();
			}

			@Override
			public void changed(LocationEvent le) {
				lastUrl = le.location;

			}
		});
	}

	private Browser browser;

	private String lastUrl = "";

}
